<?php

namespace app\admin\controller\system\files;

use app\common\controller\Backend;

use ba\Tree;
//use think\db\exception\PDOException;
//use think\exception\ValidateException;
//use think\facade\Db;

/**
 * 文件分类
 *
 */
class Category extends Backend {
    /**
     * Category模型对象
     * @var \app\admin\model\system\files\Category
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id'];

    protected array|string $quickSearchField = ['id'];

    protected $tree = null;
    protected $initValue;
    protected $assembleTree;
    protected $keyword = false;
    protected $treeAll = false;

    public function initialize():void {
        parent::initialize();
        $this->model = new \app\admin\model\system\files\Category;
        $this->tree = Tree::instance();
        $isTree = $this->request->param('isTree', true);
        $this->initValue = $this->request->get("initValue/a", '');
        $this->keyword = $this->request->request("quick_search");
        // 有初始化值时不组装树状（初始化出来的值更好看）
        $this->assembleTree = $isTree && !$this->initValue;
        $this->treeAll = empty($this->request->has('treeAll')) ? false : $this->request->get('treeAll');
    }

    public function index():void {
        if ($this->request->param('select')) {
            $this->select();
        }


        $this->success('', [
            'list' => $this->getList(),
            'remark' => get_route_remark(),
        ]);
    }

    public function select():void {
        if($this->treeAll){
            $data = $this->getList();
        }else{
            $data = $this->getList([['pid', '=', '0']]);
        }

        if ($this->assembleTree) {
            $data = $this->tree->assembleTree($this->tree->getTreeArray($data, 'name'));
        }
        $this->success('', [
            'options' => $data
        ]);
    }

    public function getList($where = []): array {
        $pk = $this->model->getPk();
        $initKey = $this->request->get("initKey/s", $pk);

        if ($this->keyword) {
            $keyword = explode(' ', $this->keyword);
            foreach ($keyword as $item) {
                $where[] = [$this->quickSearchField, 'like', '%' . $item . '%'];
            }
        }

        if ($this->initValue) {
            $where[] = [$initKey, 'in', $this->initValue];
        }
        $data = $this->model->where($where)->order('id asc')->select()->toArray();
        return $this->assembleTree ? $this->tree->assembleChild($data) : $data;
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}